package com.open.jacekkowalczyko;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

/**
 * 
 */

/**
 * mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.open.jacekkowalczyk
 * -DartifactId=simpleclient
 * 
 * @author kowalczy
 */
public class RESTClient {

    private static final Logger LOGGER = Logger.getLogger(RESTClient.class);

    /**
     * @param args
     * @throws DataConnectionException
     * @throws IOException
     * @throws UnsupportedEncodingException
     * @throws JsonMappingException
     * @throws JsonGenerationException
     */
    public static void main(final String[] args) throws UnsupportedEncodingException, IOException {

        final Properties config = new Properties();
        try {
            if (args.length == 1) {
                config.load(new FileInputStream(args[0]));
            } else {
                config.load(RESTClient.class.getClassLoader().getResourceAsStream("config.properties"));
            }
        } catch (final IOException e) {

            e.printStackTrace();
            config.put("url", "http://www.google.pl");
        }
        if (config.getProperty("print.response") == null) {
            config.put("print.response", "false");
        }
        final HttpClient httpclient = new DefaultHttpClient();
        if (config.getProperty("request.method").equalsIgnoreCase("post")) {
            post(httpclient, config);
        } else if (config.getProperty("request.method").equalsIgnoreCase("get")) {
            get(httpclient, config);
        }

    }

    private static void get(final HttpClient httpclient, final Properties config) throws UnsupportedEncodingException,
        IOException {

        // final StringEntity entity = new StringEntity(mapper.writeValueAsString(jsonParams), "UTF-8");
        // final StringEntity entity = new StringEntity(config.getProperty("body.params"), "UTF-8");
        // entity.setContentType("application/json");
        // final String bbox = config.getProperty("bbox.w") + "," + config.getProperty("bbox.n") + ","
        // + config.getProperty("bbox.e") + "," + config.getProperty("bbox.s");
        final String formatedURL = config.getProperty("url");
        final HttpGet httpget = new HttpGet(formatedURL);

        // httpget.setEntity(entity);
        System.out.println("requesting " + formatedURL);

        final HttpResponse response = httpclient.execute(httpget);

        saveResponse(config, response);

    }

    private static void saveResponse(final Properties config, final HttpResponse response) throws IOException {
        final HttpEntity entity2 = response.getEntity();
        final InputStreamReader isr = new InputStreamReader(entity2.getContent());
        final BufferedReader br = new BufferedReader(isr);
        final FileWriter fw = new FileWriter(new File("outputservice_" + config.getProperty("response.id") + ".json"));
        final BufferedWriter bw = new BufferedWriter(fw);

        for (final Header header : response.getAllHeaders()) {
            System.out.println(header.getName() + " <--> " + header.getValue());
        }

        System.out.println(response.getStatusLine().getStatusCode());

        String line;
        while ((line = br.readLine()) != null) {
            if (config.getProperty("print.response").equalsIgnoreCase("true")) {
                System.out.println(line);
            }
            bw.write(line);
        }
        br.close();
        bw.flush();
        bw.close();

        // System.out.println("\n");

        System.out.println("DONE");
    }

    private static void post(final HttpClient httpclient, final Properties config) throws UnsupportedEncodingException,
        IOException {

        final StringEntity entity = new StringEntity(config.getProperty("body.params"), "application/json", "UTF-8");
        // entity.setContentType("application/json");
        // entity.setContentEncoding("UTF-8");

        // final String bbox = config.getProperty("bbox.w") + "," + config.getProperty("bbox.n") + ","
        // + config.getProperty("bbox.e") + "," + config.getProperty("bbox.s");
        final String formatedURL = config.getProperty("url");
        final HttpPost httppost = new HttpPost(formatedURL);

        httppost.setEntity(entity);
        // System.out.println("requesting " + formatedURL + " with post body " + config.getProperty("body.params"));
        System.out.println("requesting " + formatedURL);

        final HttpResponse response = httpclient.execute(httppost);

        saveResponse(config, response);

    }

}
